﻿using System.Collections.Generic;
using System.Linq;
using Sumen.Model.Model;

namespace Sumen.Business.Presenter.Report
{
    public class ReportInwardOutwardPresenter
    {
        public ICollection<object> TotalInwardOutwardByMonthInYear(int pYear)
        {
            using (sumenEntities objEntities = new sumenEntities())
            {
                objEntities.Configuration.LazyLoadingEnabled = false;
                objEntities.Configuration.ProxyCreationEnabled = false;
                var query = from p in objEntities.stock_inward
                            where p.Inw_RefDate.Value.Year == pYear
                            group p by new { p.Inw_RefDate.Value.Month }
                                into Grouped
                                select new
                                {
                                    Month = Grouped.Max(p => p.Inw_RefDate.Value.Month),
                                    TotalInward = Grouped.Sum(p => p.Inw_Amount)
                                };
                var query1 = from p in objEntities.stock_outward
                             where p.Outw_RefDate.Value.Year == pYear
                             group p by new { p.Outw_RefDate.Value.Month }
                                 into Grouped
                                 select new
                                 {
                                     Month = Grouped.Max(p => p.Outw_RefDate.Value.Month),
                                     TotalOutward = Grouped.Sum(p => p.Outw_Amount)
                                 };
                var list = from listM in objEntities.months
                           join p in query on listM.MonthID equals p.Month into Inners1
                           from i1 in Inners1.DefaultIfEmpty()
                           join p1 in query1 on listM.MonthID equals p1.Month into Inners2
                           from i2 in Inners2.DefaultIfEmpty()
                           orderby listM.MonthID
                           select new
                           {
                               Month = listM.Name,
                               TotalInward = i1.TotalInward ?? 0,
                               TotalOutward = i2.TotalOutward ?? 0,
                               TotalTrade = (i2.TotalOutward ?? 0) - (i1.TotalInward ?? 0)
                           };
                return list.ToArray();
            }
        }


    }
}
